<template>
  <el-dialog v-model="dialogOptions.visible" :title="dialogTitle" width="1200px" append-to-body custom-class="flat-form-dialog">
    <el-form
      ref="flatFormRef"
      v-loading="dialogOptions.loading"
      :disabled="dialogOptions.type === 'view' || dialogOptions.type === 'history'"
      :rules="formRules"
      :model="data"
      label-width="110px"
    >
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>基础信息</h2>
      </div>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="公寓名称" prop="basicInfo.name">
            <el-input v-model="data.basicInfo.name" placeholder="请输入公寓名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="楼&nbsp;&nbsp;栋&nbsp;&nbsp;号" prop="basicInfo.towerNumber">
            <el-input v-model="data.basicInfo.towerNumber" placeholder="请输入楼栋号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在楼层" prop="basicInfo.floor">
            <el-input v-model="data.basicInfo.floor" placeholder="请选择所在楼层" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房&nbsp;&nbsp;间&nbsp;&nbsp;号" prop="basicInfo.roomNumber">
            <el-input v-model="data.basicInfo.roomNumber" placeholder="请输入房间号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建筑面积(㎡)" prop="basicInfo.floorArea">
            <el-input v-model="data.basicInfo.floorArea" placeholder="请输入建筑面积(㎡)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间环境" prop="basicInfo.roomEnvironment">
            <el-select v-model="data.basicInfo.roomEnvironment" placeholder="请选择房间环境">
              <el-option
                v-for="dict in parkr_building_room_environment"
                :key="`room_environment_${dict.label}`"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间状态" prop="basicInfo.roomState">
            <el-select
              v-model="data.basicInfo.roomState"
              placeholder="请选择房间状态"
              :disabled="dialogOptions.type === 'edit' && originalRoomState === 'leased'"
            >
              <el-option v-for="dict in parkbuilingroom_state" :key="`room_state_${dict.label}`" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公寓估值" prop="basicInfo.apartmentValuation">
            <el-input v-model="data.basicInfo.apartmentValuation" placeholder="请输入公寓估值" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公寓备注" prop="basicInfo.remark">
            <el-input v-model="data.basicInfo.remark" placeholder="请输入公寓备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公寓附件" prop="basicInfo.attachments">
            <file-upload v-model="data.basicInfo.attachments" placeholder="请上传公寓附件" />
          </el-form-item>
        </el-col>
      </el-row>

      <template v-if="data.basicInfo.roomState === 'leased' || dialogOptions.type == 'history'">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>租赁信息</h2>
        </div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="rentalInfo.name">
              <el-input v-model="data.rentalInfo.name" placeholder="请输入承租人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴租频次" prop="rentalInfo.frentPaymentFrequency">
              <el-select v-model="data.rentalInfo.frentPaymentFrequency" placeholder="请选择缴租频次">
                <el-option
                  v-for="dict in park_frent_payment_frequency"
                  :key="`frent_payment_frequency_${dict.label}`"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租&nbsp;&nbsp;金(元)" prop="rentalInfo.rents">
              <el-input v-model="data.rentalInfo.rents" placeholder="请输入租金" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="rentalInfo.contactInformation">
              <el-input v-model="data.rentalInfo.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期" prop="rentalInfo.startTime">
              <el-date-picker v-model="data.rentalInfo.startTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期" prop="rentalInfo.endTime">
              <el-date-picker v-model="data.rentalInfo.endTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租&nbsp;&nbsp;期(天)" prop="rentalInfo.leaseTerm">
              <el-input v-model="data.rentalInfo.leaseTerm" placeholder="自动计算" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物业费标准" prop="rentalInfo.propertyCostStandard">
              <el-input v-model="data.rentalInfo.propertyCostStandard" placeholder="请输入物业费标准" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁备注" prop="rentalInfo.remark">
              <el-input v-model="data.rentalInfo.remark" placeholder="请输入租赁备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁附件" prop="rentalInfo.attachments">
              <file-upload v-model="data.rentalInfo.attachments" placeholder="请上传租赁附件" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;租" prop="rentalInfo.surrenderTenancyStatus">
              <el-select v-model="data.rentalInfo.surrenderTenancyStatus" placeholder="请选择退租状态">
                <el-option
                  v-for="dict in park_surrender_tenancy_status"
                  :key="`surrender_tenancy_status_${dict.label}`"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租时间" prop="rentalInfo.rentOutTime">
              <el-date-picker v-model="data.rentalInfo.rentOutTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="font-size: 10px; padding-top: 10px">
              注意：选择退租后，基础信息中的房间状态变为空置房，租赁信息及收租计划将清空，您可在历史租赁信息查看！
            </div>
          </el-col>
        </el-row>

        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>收租信息</h2>
        </div>
        <div v-if="data.rentCollectionPlan.length === 0" style="text-align: right">
          <el-button type="primary" @click="handlePush()">辅助生成</el-button>
        </div>
        <h2 class="mb-5" style="text-align: center; font-weight: bold">收租计划信息</h2>
        <el-table :data="data.rentCollectionPlan" style="width: 100%" :show-summary="true" :summary-method="getSummaries">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dueDate" label="应收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>

          <el-table-column prop="rentReceivable" label="应收租金(元)">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="collect" label="是否收取" width="160">
            <template #default="scope">
              <el-radio-group v-model="scope.row.collect">
                <el-radio :value="false" size="large">否</el-radio>
                <el-radio :value="true" size="large">是</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="paidInTime" label="实收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="dialogOptions.type !== 'view' && dialogOptions.type !== 'history'">
                <el-button link type="primary" @click="handlePush(scope.$index)"> 新增 </el-button>
                <el-button link type="danger" @click="deleteRentCollectionPlan(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-else>
        <el-empty description="请将房间状态修改为已出租以添加租赁信息和收租计划" :image-size="200" />
      </template>
    </el-form>

    <template v-if="dialogOptions.type !== 'view' && dialogOptions.type !== 'history'" #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="formSubmit"> 保 存 </el-button>
        <el-button @click="dialogOptions.visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import { getFlatbasicInfo, addFlatbasicInfo, updateFlatbasicInfo } from '@/api/zichanguanli/flatbasicInfo';
import { getFlatrentalInfo, getFlathistoryRental, addFlatrentalInfo, updateFlatrentalInfo } from '@/api/zichanguanli/flatrentalInfo';
import {
  listFlatRentCollectionPlan,
  createFlatRentCollectionPlan,
  updateFlatRentCollectionPlan,
  deleteFlatRentCollectionPlan
} from '@/api/zichanguanli/flatRentCollectionPlan';
import { validateNumber, validateInteger } from '@/utils/formRules';
import { generateRentPlan, generateSingleRentPlan } from '@/utils/genRentProject';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { parkbuilingroom_state, parkr_building_room_environment, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('parkbuilingroom_state', 'parkr_building_room_environment', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

console.log(parkr_building_room_environment.value);
console.log(park_frent_payment_frequency.value);
console.log(park_surrender_tenancy_status.value);
console.log(parkbuilingroom_state.value);

const emits = defineEmits(['refresh']);

const dialogOptions = reactive({
  visible: false,
  loading: false,
  type: null
});

const originalRoomState = ref(null);

const formRules = reactive({
  'rentalInfo.contactInformation': [    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    {  required: true, message: '请填写正确的手机号码', trigger: 'change' }],
  'basicInfo.floorArea': [{ validator: validateNumber, trigger: 'blur' }],
  'basicInfo.name': [{ required: true, message: '公寓名称不能为空', trigger: 'blur' }],
  'basicInfo.apartmentValuation': [{ validator: validateNumber, trigger: 'blur' }],
  'basicInfo.floor': [{ validator: validateInteger, trigger: 'blur' }],
  'basicInfo.roomState': [{ required: true, message: '房间状态不能为空', trigger: 'blur' }],
  'rentalInfo.name': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'rentalInfo.rents': [
    { validator: validateNumber, trigger: 'blur' },
    { required: true, message: '租金不能为空', trigger: 'blur' }
  ],
  'rentalInfo.leaseTerm': [{ validator: validateInteger, trigger: 'blur' }],
  'rentalInfo.frentPaymentFrequency': [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  'rentalInfo.startTime': [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  'rentalInfo.endTime': [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
});

const flatFormRef = ref(null);
const isHistory = ref(null);

const dialogTitle = computed(() => {
  switch (dialogOptions.type) {
    case 'create':
      return '新建公寓信息';
    case 'edit':
      return '编辑公寓信息';
    case 'view':
      return '公寓信息详情';
    case 'history':
      return '公寓历史信息详情';
    default:
      return '公寓信息';
  }
});

const apartmentBasicInfoId = ref(null);

const data = reactive({
  basicInfo: {
    id: null,
    towerNumber: undefined,
    name: undefined,
    floor: undefined,
    roomNumber: undefined,
    floorArea: undefined,
    roomEnvironment: undefined,
    roomState: undefined,
    apartmentValuation: undefined,
    remark: undefined,
    attachments: undefined
  },
  rentalInfo: {
    id: null,
    name: undefined,
    frentPaymentFrequency: undefined,
    rents: undefined,
    contactInformation: undefined,
    startTime: undefined,
    endTime: undefined,
    leaseTerm: undefined,
    propertyCostStandard: undefined,
    remark: undefined,
    attachments: undefined,
    surrenderTenancyStatus: undefined,
    rentOutTime: undefined
  },
  rentCollectionPlan: []
});

const formDialogDataInit = async () => {
  console.log(123);

  try {
    let basicInfoRes = {};
    if (isHistory.value == true) {
      basicInfoRes = await getFlathistoryRental(apartmentBasicInfoId.value);
    } else {
      basicInfoRes = await getFlatbasicInfo(apartmentBasicInfoId.value);
    }
    console.log(basicInfoRes);
    data.basicInfo = basicInfoRes.data.apartmentBasicInfoVo || {};
    data.rentalInfo = basicInfoRes.data.apartmentRentalInfoVo || {};
    data.rentCollectionPlan = basicInfoRes.data.apartmentRentCollectionPlanVoList || [];
    // const rentalInfoRes = await getFlatrentalInfo(apartmentBasicInfoId.value);
    // const rentCollectionPlanRes = await listFlatRentCollectionPlan({ apartmentBasicInfoId: apartmentBasicInfoId.value });

    // for (const key in data.basicInfo) {
    //   data.basicInfo[key] = basicInfoRes.data[key];
    // }

    // for (const key in data.rentalInfo) {
    //   data.rentalInfo[key] = rentalInfoRes.data[key];
    // }

    // data.rentCollectionPlan = rentCollectionPlanRes.rows;
  } catch (error) {
    proxy?.$modal.msgError(`数据加载失败，${error}`);
  }
};

const formReset = async () => {
  for (const key in data.basicInfo) {
    data.basicInfo[key] = undefined;
  }

  data.basicInfo.roomState = 'in_idle';
  originalRoomState.value = undefined;

  for (const key in data.rentalInfo) {
    data.rentalInfo[key] = undefined;
  }

  data.rentCollectionPlan = [];
};

const formSubmit = async () => {
  const valid = await flatFormRef.value.validate();
  if (!valid) return;
  try {
    dialogOptions.loading = true;
    if (dialogOptions.type == 'create') {
      const datas = {
        apartmentBasicInfoBo: data.basicInfo,
        apartmentRentalInfoBo: data.rentalInfo,
        apartmentRentCollectionPlanBoList: data.rentCollectionPlan
      };
      await addFlatrentalInfo(datas);
    } else if (dialogOptions.type == 'edit') {
      const basicInfo = {
        apartmentBasicInfoBo: data.basicInfo,
        apartmentRentalInfoBo: data.rentalInfo,
        apartmentRentCollectionPlanBoList: data.rentCollectionPlan
      };
      await updateFlatrentalInfo(basicInfo);
    }

    emits('refresh');
  } catch (error) {
    console.log('数据提交失败', error);
    // proxy?.$modal.msgError(`数据提交失败，${error}`);
  } finally {
    dialogOptions.loading = false;
    dialogOptions.visible = false;
  }
};

const handlePush = (index?: number) => {
  // 如果传入了 index，说明是在指定位置插入新记录
  if (typeof index === 'number') {
    // 确保 rentCollectionPlan 存在
    if (!data.rentCollectionPlan) {
      data.rentCollectionPlan = [];
    }

    // 生成新的收租计划记录
    const newPlan = generateSingleRentPlan();

    // 在指定位置后插入新记录
    data.rentCollectionPlan.splice(index + 1, 0, newPlan);
    ElMessage.success('添加成功');
    return;
  }

  // 以下是原有的批量生成逻辑
  const rentalInfo = data.rentalInfo;
  if (!rentalInfo) {
    ElMessage.warning('租赁信息不存在');
    return;
  }

  const { frentPaymentFrequency, rents, startTime, endTime } = rentalInfo;

  // 检查所有必要字段
  if (!frentPaymentFrequency) {
    ElMessage.warning('请先填写缴租频次');
    return;
  }
  if (!rents) {
    ElMessage.warning('请先填写租金');
    return;
  }
  if (!startTime) {
    ElMessage.warning('请先填写开始时间');
    return;
  }
  if (!endTime) {
    ElMessage.warning('请先填写结束时间');
    return;
  }

  // 生成收租计划
  try {
    const rentPlans = generateRentPlan({
      frequencyOfRentPayments: frentPaymentFrequency,
      rents: Number(rents),
      startTime,
      endTime
    });
    data.rentCollectionPlan = rentPlans;
    ElMessage.success('收租计划生成成功');
  } catch (error) {
    console.error('生成收租计划失败:', error);
    ElMessage.error('生成收租计划失败，请检查输入数据');
  }
};

const deleteRentCollectionPlan = async (index: number, row: any) => {
  if (row.id) {
    await deleteFlatRentCollectionPlan(row.id);
    data.rentCollectionPlan.splice(index, 1);
  } else {
    data.rentCollectionPlan.splice(index, 1);
  }
};

const open = async (type: string, id: string | number) => {
  dialogOptions.type = type;
  dialogOptions.visible = true;
  dialogOptions.loading = true;
  nextTick(() => formReset());

  switch (dialogOptions.type) {
    case 'edit':
    case 'view':
      apartmentBasicInfoId.value = id;
      await formDialogDataInit();
      originalRoomState.value = data.basicInfo.roomState;
      break;
    case 'history':
      apartmentBasicInfoId.value = id;
      isHistory.value = true;
      await formDialogDataInit();
      break;
  }
  dialogOptions.loading = false;
};
defineExpose({ open });

const calculateTotal = () => {
  return data.rentCollectionPlan
    .reduce((sum, item) => {
      return sum + (Number(item.rentReceivable) || 0);
    }, 0)
    .toFixed(2);
};

const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (column.property === 'rentReceivable') {
      const values = data.map((item) => Number(item.rentReceivable) || 0);
      sums[index] = values
        .reduce((prev, curr) => {
          return prev + curr;
        }, 0)
        .toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 监听开始时间和结束时间的变化，自动计算租期
watch([() => data.rentalInfo.startTime, () => data.rentalInfo.endTime], ([newStartTime, newEndTime]) => {
  if (newStartTime && newEndTime) {
    const start = dayjs(newStartTime);
    const end = dayjs(newEndTime);
    // 计算天数差
    const days = end.diff(start, 'day') + 1; // +1 是因为包含结束当天
    data.rentalInfo.leaseTerm = days.toString();
  } else {
    data.rentalInfo.leaseTerm = '';
  }
});

// 监听房间状态变化
watch(
  () => data.basicInfo.roomState,
  (newStatus) => {
    if (newStatus !== 'leased' && dialogOptions.type != 'history' && dialogOptions.type != 'detail') {
      // 如果切换到非已出租状态，清空租赁信息和收租计划
      data.rentalInfo = {
        id: null,
        name: undefined,
        frentPaymentFrequency: undefined,
        rents: undefined,
        contactInformation: undefined,
        startTime: undefined,
        endTime: undefined,
        leaseTerm: undefined,
        propertyCostStandard: undefined,
        remark: undefined,
        attachments: undefined,
        surrenderTenancyStatus: undefined,
        rentOutTime: undefined
      };
      data.rentCollectionPlan = [];
    } else if (newStatus === 'leased' && dialogOptions.type != 'history' && dialogOptions.type != 'detail') {
      // 当状态为已租赁时，设置退租状态为在租
      data.rentalInfo.surrenderTenancyStatus = 'under_rent';
    }
  }
);
</script>
